package com.example.springboot.controller.requstParams;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * request域参数的获取
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/8 23:07
 */
@Controller
public class RequestAttributeController {
    @GetMapping("/goto")
    public String goToPage(HttpServletRequest request) {
        request.setAttribute("msg", "成功了");
        request.setAttribute("code", 200);
        return "forward:/success";
    }

    /**
     * 获取request域的参数
     *
     * @param msg
     * @param code
     * @return
     */
    @GetMapping("/success")
    @ResponseBody
    public Map<String, Object> success(@RequestAttribute(value = "msg",required = false) String msg,
                                       @RequestAttribute(value = "code",required = false) Integer code,
                                       HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("msg", msg);
        map.put("code", code);
        // 从request域中获取
        Object attribute = request.getAttribute("hello");
        Object attribute1 = request.getAttribute("world");
        Object attribute2 = request.getAttribute("message");
        Object msg1 = request.getAttribute("msg");
        map.put("reqMethod_msg", msg1);
        map.put("annotation", msg);
        map.put("hello", attribute);
        map.put("world", attribute1);
        map.put("message", attribute2);
        return map;
    }
}
